﻿#region << 文件说明 >>

/*----------------------------------------------------------------
 * 命名空间：Vampirewal.Core.WebApi
 * 唯一标识：b0f1f8c9-a55f-4c7d-9b9c-9907ca8b9a9a
 * 文件名：VampirewalActionFilterPipeline
 *
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2023/10/9 15:35:50
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion << 文件说明 >>

namespace Vampirewal.Core.WebApi;

/// <summary>
/// 方法拦截器管道
/// </summary>
internal sealed class VampirewalActionFilterPipeline
{
    private readonly IReadOnlyList<IVampirewalActionFilter> _ActionFilters;

    public VampirewalActionFilterPipeline(IReadOnlyList<IVampirewalActionFilter> ActionFilters)
    {
        _ActionFilters = ActionFilters;
    }

    public async Task<bool> InvokeAsync(IVampirewalActionFilterContext context)
    {
        var index = -1;

        Func<Task<bool>>? nextActionFilter = null;
        nextActionFilter = async () =>
        {
            index++;

            if (index < _ActionFilters.Count)
            {
                var attr = _ActionFilters[index];
                try
                {
                    return await attr.ExcuteActionAsync(context, nextActionFilter);
                }
                catch (Exception ex)
                {
                    context.ErrorInfo = $"拦截器:{attr.GetType().Name},错误信息:{ex.Message}";
                }
            }

            return await Task.FromResult(context.IsSuccess);
        };

        return await nextActionFilter();
    }
}